package org.miniframework.server;

import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.miniframework.mvc.DispatcherServlet;
import org.miniframework.util.FileUtil;

public class TestTomcat {

    private static int PORT = 8080;
    private static String CONTEX_PATH = "/tomcat";
    private static String SERVLET_NAME = "hello";
    private static String MAPPING = "test";

    public static void main(String[] args) throws Exception {
        loadBanner();
        System.out.println("开始启动tomcat");
        Tomcat tomcatServer = new Tomcat();
        //设置tomcat端口
        tomcatServer.setPort(PORT);
        //此tomcat端口是否自动部署
        tomcatServer.getHost().setAutoDeploy(false);
//        Context ctx = tomcatServer.addWebapp("/", new File("src/main/webapp").getAbsolutePath());
//        WebResourceRoot standardRoot = new StandardRoot(ctx);
        //创建一个web应用程序
        Context ctx = new StandardContext();
        //设置web应用程序的上下文地址
        ctx.setPath(CONTEX_PATH);
        //添加web应用程序的监听
        ctx.addLifecycleListener(new Tomcat.FixContextListener());
        //将web应用程序添加到服务器中
        tomcatServer.getHost().addChild(ctx);
        //配置servelt和映射
        tomcatServer.addServlet(CONTEX_PATH, SERVLET_NAME, new DispatcherServlet());
        ctx.addServletMappingDecoded("/"+MAPPING, SERVLET_NAME);

        String sourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        WebResourceRoot resources = new StandardRoot(ctx);
        resources.addPreResources(new DirResourceSet(resources,"/WEB-INF/classes",sourcePath,"/"));

        ctx.setResources(resources);


        //启动tomcat
        tomcatServer.start();
        System.out.println("启动tomcat完毕");
        //开启异步服务，接收请求
        tomcatServer.getServer().await();
    }

    public static void loadBanner(){
        String fileName = "banner.txt";
        String projectPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String content = FileUtil.read(projectPath+fileName);
        if (content != null && content.contains("xiaochi")){
            content = content.replace("xiaochi","\033[35;4mxiaochi\033[0m");
        }
        System.out.println(content);
    }
}
